let _baseUrl = getBaseUrl();
_baseUrl = baseUrl.substr(0,_baseUrl.indexOf('/index.php'));

const Yuerjing_list = React.createClass({
    getDefaultProps(){
        return({
            data: []
        });
    },
    getInitialState(){
        return({
            is_like: parseInt(this.props.data.is_like) ? true : false,
            favorites:  parseInt(this.props.data.is_fav) ? true : false,
            is_focus: parseInt(this.props.data.is_focus) ? true : false,
            loading: false
        });
    },
    like(){

        if(this.state.is_like){
            message.error('已经点过赞了');
            return;
        }

        if(this.state.loading) return;

        let post = this.props.data;

        let url = getBaseUrl() + '/mengwu/mengwuApi/post_like';
        let data = {
            tid: post.tid
        };
        

        this.setState({loading:true});

        _post(url,jQuery.param(data),{data_back: function(data){
            if(data.status){
                this.setState({is_like: true,loading:false});
            }else{
                this.setState({loading:false});
                if(typeof data.info.redirect !="undefined"){
                    window.location.href = data.info.redirect;
                }
            }
        }.bind(this)});

    },
    fav(){

        if(this.state.loading)return;

        //收藏
        let data = {
            tid: this.props.data.tid,
            favorite_value : 1
        };
        let favorites = true;
        if(this.state.favorites){
            data.favorite_value = 0;
            //取消收藏
            favorites = false;
        }

        let url = getBaseUrl() + '/mengwu/mengwuApi/post_favorites';

        this.setState({loading:true});

        _post(url,jQuery.param(data),{data_back: function(data){
            if(data.status){
                if(favorites){
                    message.success('收藏成功！');
                }else{
                    message.success('取消成功！');
                }
                this.setState({favorites: favorites,loading:false});
            }else{
                this.setState({loading:false});
                if(typeof data.info.redirect !="undefined"){
                    window.location.href = data.info.redirect;
                }
            }
        }.bind(this)});
    },
    focus(){

        if(this.state.loading)return;

        //关注
        let data = {
            focus_uid : this.props.data.author_id,
            value : 1
        };
        let focus = true;
        if(this.state.is_focus){
            data.value = 0;
            //取消收藏
            focus = false;
        }

        let url = getBaseUrl() + '/mengwu/mengwuApi/user_focus';

        this.setState({loading:true});

        _post(url,jQuery.param(data),{data_back: function(data){
            if(data.status){
                if(focus){
                    message.success('关注成功！');
                }else{
                    message.success('取消成功！');
                }
                this.setState({is_focus: focus,loading:false});
            }else{
                this.setState({loading:false});
                if(typeof data.info.redirect !="undefined"){
                    window.location.href = data.info.redirect;
                }else{
                    message.error(data.info);
                }
            }
        }.bind(this)});

    },
    render(){
        let data = this.props.data;
        let baby_default = [];
        if(typeof data.baby_default !=='undefined'){
            let val = data.baby_default;
            let sex = '女宝';
            if(sex==1) sex = '男宝';
            let age = '';
            let now = new Date();
            let birth = new Date(val.birthday * 1000);
            let y = now.getYear() - birth.getYear();
            let m = now.getMonth() - birth.getMonth();
            let d = now.getDate() - birth.getDate();

            baby_default.push(<span>{sex}</span>);
            
            if(d<0){
                m--;
                if(m<0){
                    y--;
                    m += 12;
                }
                d += (new Date(y,m,0)).getDate();
            }
            if(y>=0){
                age = y + '岁' + m + '月' + d + '天';
                baby_default.push(<span>{age}</span>);
            }
        }
        let pics = [];
        if(typeof data.img !=='undefined'){
            pics = data.img.map(function(val){
                return <div className="ylj-pic"><img src={val + '&size=160'} onClick={function(){this.props.picClick(val)}.bind(this)} /></div>
            }.bind(this));
        }
        let replyCount = typeof data.reply_info.count!=='undefined' ? data.reply_info.count : 0;
        let likes = typeof data.likes!=='undefined' ? data.likes : 0;
        let fav = '收藏';
        let focus = '关注';
        if(this.state.favorites) fav = '取消收藏';
        if(this.state.is_focus) focus = '取消关注';
        if(this.state.is_like) likes ++ ;

        return(
            <div className="yej-list">
                <div className="yej-list-top">
                    <div className="yej-list-top-left">
                        <img src={data.head} />
                    </div>
                    <div className="yej-list-top-right">
                        <div className="yej-list-top-left-top">
                            {data.author}<a className="btn btn-focus" href="javascript:void(0);" onClick={this.focus}>{focus}</a>
                        </div>
                        <div className="yej-list-top-left-bottom">
                            {baby_default}
                        </div>
                    </div>
                </div>
                <div className="yej-list-middle">
                    <span className="yej-title">{data.subject}</span><br />
                    {data.message}
                </div>
                <div className="yej-list-pics">
                    {pics}
                </div>
                <div className="yej-list-bottom">
                    <div className="fl">
                        <a href={getBaseUrl() + '/mengwu/yuerjing/detail/type/' + yej_post_type +'/tid/' + data.tid} target="_blank"><img src={_baseUrl+'/Public/Mengwu/img/yuerjing/pinglun.png'} />评论（{replyCount}）</a>
                        <a href="javascript:void(0);" onClick={this.fav}><img src={_baseUrl+'/Public/Mengwu/img/yuerjing/shoucang.png'} />{fav}</a>
                        <a href="javascript:void(0);" onClick={this.like}><img src={_baseUrl+'/Public/Mengwu/img/yuerjing/zan.png'} />赞（{likes}）</a>
                    </div>
                    <div className="fr">
                        <img src={_baseUrl+'/Public/Mengwu/img/yuerjing/dateline.png'} />{data.dateline_show}
                    </div>
                </div>
            </div>
        );
    }
});

const { Pagination,Modal,Popconfirm,Spin } = antd;

const Yuerjing = React.createClass({
    getInitialState(){
        let nowPage = window.location.hash;
        nowPage = parseInt(nowPage.split('#')[1]);
        nowPage = nowPage || 1;
        return({
            nowPage: nowPage,
            num: 0,
            page_size: 5,
            posts:[],
            loading: true,
            labels: yej_hot_labels,
            label_selected: 0,
            pic_browser_show: false,
            pic_browser_img: ''
        });
    },
    componentDidMount(){
        this.jumpPage(this.state.nowPage);
    },
    hashChange(){
        window.location.reload();
    },
    jumpPage(page_no,tag_id=0){
        let url = getBaseUrl() + '/mengwu/mengwuApi/yuerjing_post_query/type/'+yej_post_type;
        let data = {
            page_no: page_no,
            page_size: this.state.page_size,
            tag_id: tag_id
        };
        _post(url,jQuery.param(data),{data_back: function(data){
            if(data.status){
                window.location.hash = page_no;
                this.setState({posts: data.info.list, num: data.info.count, loading: false, nowPage: page_no});
            }else{
                if(typeof data.info.redirect !="undefined"){
                    window.location.href = data.info.redirect;
                }
            }
        }.bind(this)});
    },
    PaginationChange(page){
        this.setState({loading: true,posts: []});
        $('html, body').animate({
            scrollTop: 0
        }, 200);
        this.jumpPage(page,this.state.tag_id);
    },
    labelClick(tag_id){
        this.setState({loading: true,posts: [], label_selected: tag_id});
        this.jumpPage(this.state.nowPage,tag_id);
    },
    hide_pic_browser(){
        this.setState({pic_browser_show: false,pic_browser_img:''});
    },
    show_pic_browser(img_url){
        this.setState({
            pic_browser_img: img_url,
            pic_browser_show: true
        });
    },
    render(){
        let list = this.state.posts.map(function(val){
            return(
                <Yuerjing_list data={val} picClick={this.show_pic_browser}/>
            );
        }.bind(this));

        let page = [];
        if(!this.state.loading){
            if(this.state.posts.length!=0){
                page =
                    <div className="pagination-wrap">
                        <div className="pagination-middle">
                            <Pagination current={this.state.nowPage} total={this.state.num} pageSize={this.state.page_size} onChange={this.PaginationChange} />
                        </div>
                    </div>
            }else{
                list = <div className="text-center">没有任何帖子哟~</div>
            }

        }
        let labels = this.state.labels.map(function(val){
            let cl = 'hot-label';
            if(this.state.label_selected == val.id) cl +=' selected';
            if(val.hot) cl +=' hot';
            return <a className={cl} onClick={function(){return this.labelClick(val.id)}.bind(this)}>{val.name}</a>;
        }.bind(this));

        return(
            <Spin spinning={this.state.loading}>
                <Modal visible={this.state.pic_browser_show} footer={false} width="900" onCancel={this.hide_pic_browser} style={{top:50}}>
                    <div className="pic-browser">
                        <img src={this.state.pic_browser_img} onClick={this.hide_pic_browser} />
                    </div>
                </Modal>
                <div className="hot-labels">
                    <a className={this.state.label_selected==0 ? 'hot-label selected': 'hot-label'} onClick={function(){return this.labelClick(0)}.bind(this)}>全部</a>
                    {labels}
                </div>
                <div className="posts-list">
                    {list}
                    {page}
                </div>
            </Spin>
        );
    }
});

const Btn_publish = React.createClass({
    getInitialState(){
        return({
            show_modal: false,
            loading: false,
            dropzone: false,
            addlabel: false,
            used_labels: [],
            labels:yej_hot_labels,
            content: {
                subject:'',
                message: '',
                attachments: []

            }
        });
    },
    modalShow(){
        this.setState({show_modal: true});
    },
    modalHide(){
        yej_piclist = [];
        let dropzone = this.state.dropzone;
        dropzone.removeAllFiles(true);
        this.setState({
            show_modal: false,
            used_labels: [],
            content: {
                subject:'',
                message: '',
                attachments: []
            },
            addlabel: false
        });
    },
    titleOnchange(event){
        let content = this.state.content;
        content.subject = event.target.value;
        this.setState({content: content});
    },
    messageOnchange(event){
        let content = this.state.content;
        content.message = event.target.value;
        this.setState({content: content});
    },
    componentDidUpdate(){
        let myDropzone = this.refs.myDropzone;
        let dropzone = this.state.dropzone;
        if(!dropzone && typeof myDropzone !=='undefined'){
            dropzone = new Dropzone(myDropzone);
            this.setState({dropzone: dropzone});
        }
    },
    //点击发布
    handleOk(){
        let content = this.state.content;
        if($.trim(content.message)==''){
            message.error('内容不能为空或纯空白字符!');
            this.refs.message_textarea.focus();
            return;
        }

        this.setState({loading: true});
        let url = getBaseUrl() + '/mengwu/mengwuApi/yuerjing_post_add/type/'+yej_post_type;


        let attachments = yej_piclist.map(function(val){
            return val.id;
        });
        let used_labels = this.state.used_labels;
        let data = {
            subject: content.subject,
            message: content.message,
            attachments: attachments.join(','),
            tags: used_labels.join(',')
        };

        _post(url,jQuery.param(data),{data_back: function(data){
            if(data.status){
                message.success('发布成功!');
                setTimeout(function(){
                    this.setState({loading: false, show_modal: false});
                    window.location.href = window.location.href;
                }.bind(this),1000);
            }else{
                if(typeof data.info.redirect !="undefined"){
                    message.error(data.info.info);
                    setTimeout(function(){
                        window.location.href = data.info.redirect;
                    }.bind(this),1000);
                }else{
                    message.error(data.info);
                }
            }
        }.bind(this)});
    },
    addlabelClick(){
        this.setState({addlabel: true});
    },
    cancelAddLabel(){
        this.refs.label_input.value = '';
        this.setState({addlabel: false});
    },
    addLabelOK(){
        let label_input = this.refs.label_input;
        let new_label = $.trim(label_input.value);
        let used_labels = this.state.used_labels;
        let add = true;
        label_input.value = '';
        if(new_label==''){
            message.error('新标签不能为空!');
            label_input.focus();
            return;
        }else if(new_label=='全部'){
            message.error('不能添加此标签!');
            label_input.focus();
            return;
        }else{
            used_labels.forEach(function(val){
                if(val==new_label)add = false;
            });
            if(add){
                used_labels.push(new_label);
            }
        }
        this.setState({addlabel: false, used_labels: used_labels});
    },
    labels_click(text){
        let used_labels = this.state.used_labels;
        let add = true;
        used_labels = used_labels.filter(function(val){
            if(val==text){
                add = false;
            }else{
                return true;
            }
        });

        if(add){
            used_labels.push(text);
        }
        this.setState({used_labels: used_labels});
    },
    uesed_labels_click(text){
        let used_labels = this.state.used_labels;
        used_labels = used_labels.filter(function(val){
            if(val!=text)return true;
        });
        this.setState({used_labels: used_labels});
    },
    render(){
        let up_url = getBaseUrl() + '/mengwu/fileupload/index/bbs';
        let addlabel = this.state.addlabel;
        let addlabelbtnST = addlabel?{display:'none'}:{};
        let addlabelinputST = !addlabel?{display:'none'}:{};
        let used_labels_hash = [];
        //已使用标签
        let used_labels = this.state.used_labels.map(function(val){
            used_labels_hash[val] = true;
            return(
                <Popconfirm title="要删除这个标签吗？" onConfirm={function(){return(this.uesed_labels_click(val))}.bind(this)}>
                    <a className="hot-label">{val}</a>
                </Popconfirm>
            );
        }.bind(this));
        //热门标签
        let labels = this.state.labels.map(function(val){
            let cl = 'hot-label';
            if(used_labels_hash[val.name]) cl += ' selected';
            if(val.hot) cl +=' hot';
            return(
                <a className={cl} onClick={function(){return(this.labels_click(val.name))}.bind(this)}>{val.name}</a>
            );

        }.bind(this));
        let content =this.state.content;
       return(
            <a className="btn-publish" onClick={this.modalShow}>
                <Modal visible={this.state.show_modal} onOk={this.handleOk} onCancel={this.modalHide} closable={false} okText="发布" confirmLoading={this.state.loading}>
                        <Spin spinning={this.state.loading}>
                            <div className="yuerjing-pub-wrap">
                                <div className="title">育儿经发布</div>
                                <div className="pub-box">
                                    <div className="pb-top">
                                        <div className="pb-title">
                                            <input type="text" placeholder="标题（选填）" onChange={this.titleOnchange} value={content.subject} />
                                        </div>
                                        <div className="pb-content">
                                            <textarea ref="message_textarea" placeholder="请输入内容..." onChange={this.messageOnchange} value={content.message} />
                                            <div className="pic-wrap">
                                                <form action={up_url} className="dropzone" id="myDropzone" ref="myDropzone">
                                                    <div className="fallback">
                                                        <input name="file" type="file" multiple />
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="pb-bottom">
                                        <div className="pb-sort">
                                            <div className="s">
                                                <h4>分类</h4>
                                                <span>{yej_post_type_desc}</span>
                                            </div>
                                            <div className="add">
                                                <h4>添加标签</h4>
                                                <div className="add-labels">
                                                    {used_labels}
                                                    <a onClick={this.addlabelClick} style={addlabelbtnST} href="javascript:void(0);" className="btn-addlabel"><i className="iconfont icon-plus"></i></a>
                                                    <div className="add-new-labels" style={addlabelinputST}>
                                                        <input ref="label_input" type="text" placeholder="添加新标签" />
                                                        <a href="javascript:void(0);" className="btn btn-add-new-l" onClick={this.addLabelOK}>添加</a>
                                                        <a href="javascript:void(0);" className="btn btn-cancel-new-l" onClick={this.cancelAddLabel}>取消</a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="pb-labels">
                                            {labels}
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </Spin>
                    </Modal>
            </a>
        );
    }
});

ReactDOM.render(
    <Yuerjing />,
    document.getElementById('posts_list')
);

ReactDOM.render(
    <Btn_publish />,
    document.getElementById('btn_publish')
);
